package com.magist.core.redis;


import com.magist.core.auth.AuthUser;
import com.magist.core.constants.AppConstants;
import com.magist.core.constants.AppParams;
import com.magist.core.helper.SessionHelper;
import com.magist.core.http.HttpHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Service;

import java.io.Serializable;

/**
 * session 查询处理
 * 
 * @author zhuangja
 *
 */
public class RedisSessionHelperImpl implements SessionHelper {

	private RedisExecutor redisExecutor;

	@Override
	public void set(String key, Serializable value) {
		this.set(key, value, AppParams.SESSION_KEEP_TIME);
	}

	@Override
	public Object get(String key) {
		redisExecutor.expire(buildKey(key), AppParams.SESSION_KEEP_TIME);
		return redisExecutor.get(buildKey(key));
	}

	@Override
	public void set(String key, Serializable value, int keeplive) {
		redisExecutor.set(buildKey(key), value);
		redisExecutor.expire(buildKey(key), keeplive);
	}

	@Override
	public void del(String key) {
		redisExecutor.del(buildKey(key));
	}

	@Override
	public void setUser(AuthUser user) {
		this.set(AppConstants.SESSION_USER_KEY, user, AppParams.SESSION_KEEP_TIME);
	}

	@Override
	public AuthUser getUser() {
		Object o = this.get(AppConstants.SESSION_USER_KEY);
		if (o != null)
			return (AuthUser) o;
		return null;
	}

	public void setRedisExecutor(RedisExecutor redisExecutor) {
		this.redisExecutor = redisExecutor;
	}

	private String buildKey(String key) {
		return HttpHolder.getHttpRequest().getSession().getId() + ":" + key;
	}

	@Override
	public void clearUser() {
		this.del(AppConstants.SESSION_USER_KEY);
	}


	@Override
	public Long generateAutoIncrId(String key) {
		RedisAtomicLong counter = new RedisAtomicLong(key, redisExecutor.getRedisTemplate().getRequiredConnectionFactory());
		return counter.incrementAndGet();
	}
}
